﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ThreeByte.ActiveDeck.Config;
using ThreeByte.ActiveDeck.Service;
using System.Xml.Linq;
using ThreeByte.ActiveDeck.Data;
using log4net;
using System.Diagnostics;
using System.Net;

namespace ThreeByte.ActiveDeck.AddIn.Controls
{
    /// <summary>
    /// Interaction logic for NamePresentationControl.xaml
    /// </summary>
    public partial class NamePresentationControl : UserControl
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(NamePresentationControl));

        public event EventHandler<DialogResultEventArgs> Close;
        public CoreConfig Config;

        public NamePresentationControl(CoreConfig config, NetworkCredential creds = null, bool rename = false) {
            InitializeComponent();

            Config = config;

            if(string.IsNullOrEmpty(config.Name)) {
                //Add a default name from the power point file
                string defaultName = Globals.ThisAddIn.Application.ActivePresentation.Name;
                if(defaultName != null) {
                    if(defaultName.EndsWith(@".pptx")) {
                       defaultName = defaultName.Replace(@".pptx", string.Empty);
                    }
                }
                PresentationNameTextBox.Text = defaultName;
            } else {
                PresentationNameTextBox.Text = config.Name;    
            }
            
            if (rename) {
                PromptTextBlock.Text = "Please enter a new name for your presentation:";
                CreateButton.Visibility = System.Windows.Visibility.Collapsed;
                RenameButton.Visibility = System.Windows.Visibility.Visible;

                //Disable modifying user credentials
                PresenterUserNameTextBox.IsEnabled = false;
                PresenterUserNameTextBox.ToolTip = "In order to change the presenter login, please create a new presentation ID";

                //If credentials already entered, collapse the Login expander
                PresenterLoginExpander.IsExpanded = false;
            }

            PresentationNameTextBox.SelectAll();
            PresentationNameTextBox.Focus();


            if (creds != null) {
                PresenterUserNameTextBox.Text = creds.UserName;
                PresenterPasswordTextBox.Password = creds.Password;
            } else {
                PresenterUserNameTextBox.Text = Config.PresenterLogin.UserName;
                PresenterPasswordTextBox.Password = Config.PresenterLogin.Password;
            }
            
        }

        private void PresenterPasswordTextBox_PasswordChanged(object sender, RoutedEventArgs e) {
            
        }

        private void Hyperlink_Click(object sender, RoutedEventArgs e) {
            Hyperlink link = (Hyperlink)sender;
            try {
                string webAddress = link.NavigateUri.AbsoluteUri;
                ProcessStartInfo ps = new ProcessStartInfo(webAddress);
                ps.UseShellExecute = true;
                Process.Start(ps);
            } catch(Exception ex) {
                log.Error("Could not open address", ex);
            }
        }

        private void CreateButton_Click(object sender, RoutedEventArgs e) {

            InvalidUsernamePopup.IsOpen = false;

            //Store the new Presentation Login Info
            PresenterUserNameTextBox.IsEnabled = false;
            PresenterPasswordTextBox.IsEnabled = false;

            Config.PresenterLogin.UserName = PresenterUserNameTextBox.Text;
            Config.PresenterLogin.Password = PresenterPasswordTextBox.Password;

            //Do it.
            WebServiceClient client = new WebServiceClient(Config.PresenterLogin);
            XElement response = null;

            try {

                response = client.NewPresentation(PresentationNameTextBox.Text);

                PresentationHeader newPres = new PresentationHeader(response);

                Config.ID = newPres.ID;
                Config.Name = newPres.Name;
                Config.MarkAsDirty();

                //Great, show the presentation ID
                StatusTextBlock.Text = "Success!  Your Presentation ID is:";
                StatusTextBlock.Visibility = System.Windows.Visibility.Visible;

                PresentationIDTextBlock.Text = newPres.ID;
                PresentationIDTextBlock.Visibility = System.Windows.Visibility.Visible;

                PresentationNameTextBox.IsEnabled = false;

                CreateButton.Visibility = System.Windows.Visibility.Collapsed;
                DoneButton.Visibility = System.Windows.Visibility.Visible;

                CancelButton.IsEnabled = false;

            } catch (Exception ex) {
                if(response != null && response.Name == "Error") {
                    string domain = response.Attribute("Domain").Value;
                    string message = response.Attribute("Message").Value;

                    if(domain == "Authentication"
                        || domain == "Authorization") {
                        LoginErrorTextBlock.Text = message;
                        InvalidUsernamePopup.IsOpen = true;
                    } else {
                        //Some other problem
                        LoginErrorTextBlock.Text = message;
                        InvalidUsernamePopup.IsOpen = true;
                    }

                    //TODO: Or show the exception?
                } else {
                    LoginErrorTextBlock.Text = "There was an error creating your presentation.  Please check your internet connection";
                    InvalidUsernamePopup.IsOpen = true;
                }
                log.Error("Error creating presentation", ex);
                //Console.WriteLine("Response: {0}", response.ToString());
                PresenterUserNameTextBox.IsEnabled = true;
                PresenterPasswordTextBox.IsEnabled = true;
            }
        }

        private void RenameButton_Click(object sender, RoutedEventArgs e) {

            InvalidUsernamePopup.IsOpen = false;

            //Store the new Presentation Login Info
            Config.PresenterLogin.UserName = PresenterUserNameTextBox.Text;
            Config.PresenterLogin.Password = PresenterPasswordTextBox.Password;

            //Do it.
            WebServiceClient client = new WebServiceClient(Config.PresenterLogin);
            XElement response = null;

            try {
                response = client.RenamePresentation(Config.ID, PresentationNameTextBox.Text);
                PresentationHeader newPres = new PresentationHeader(response);

                Config.Name = newPres.Name;
                Config.MarkAsDirty();

                //Great, show the presentation ID
                StatusTextBlock.Text = "Success!  Your Presentation has been renamed.";
                StatusTextBlock.Visibility = System.Windows.Visibility.Visible;

                PresentationNameTextBox.IsEnabled = false;

                RenameButton.Visibility = System.Windows.Visibility.Collapsed;
                DoneButton.Visibility = System.Windows.Visibility.Visible;

                CancelButton.IsEnabled = false;
            } catch (Exception ex) {
                log.Debug("Problem renaming presentation", ex);
                if(response != null && response.Name == "Error") {
                    string domain = response.Attribute("Domain").Value;
                    string message = response.Attribute("Message").Value;

                    if (domain == "Authentication"
                        || domain == "Authorization") {
                        LoginErrorTextBlock.Text = message;
                        InvalidUsernamePopup.IsOpen = true;
                    } else {
                        //Some other problem
                        LoginErrorTextBlock.Text = message;
                        InvalidUsernamePopup.IsOpen = true;
                    }
                } else {
                    LoginErrorTextBlock.Text = "There was an error creating your presentation.  Please check your internet connection";
                    InvalidUsernamePopup.IsOpen = true;
                }
                log.InfoFormat("Response: {0}", response);
            }
        }


        private void CancelButton_Click(object sender, RoutedEventArgs e) {
            //Cancel the transactional operation before closing the window
            if(Close != null) {
                Close(this, new DialogResultEventArgs(System.Windows.Forms.DialogResult.Cancel));
            }
        }

        private void DoneButton_Click(object sender, RoutedEventArgs e) {
            if(Close != null) {
                Close(this, new DialogResultEventArgs(System.Windows.Forms.DialogResult.OK));
            }
        }

        private void PresenterPasswordTextBox_PreviewKeyDown(object sender, KeyEventArgs e) {
            if(e.Key == Key.Enter || e.Key == Key.Return) {
                CreateButton_Click(null, null);
            }
        }

        private void PresentationNameTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) {
            e.Handled = !(IsTextAllowed(e.Text));
        }

        private bool IsTextAllowed(string text) {
            foreach(char c in text.ToCharArray()) {
                if(Char.IsLetterOrDigit(c)
                    || c == '_'
                    || c == '-'
                    || c == '('
                    || c == ')'
                    || c == '\''
                    || c == '.'
                    || c == '!'
                    || c == '$'
                    || c == ','
                    || c == ';') {

                } else {
                    return false;
                }
            }
            return true;

        }

        private void PresentationNameTextBox_Pasting(object sender, DataObjectPastingEventArgs e) {
            if(e.DataObject.GetDataPresent(typeof(string))) {
                string text = (string)e.DataObject.GetData(typeof(string));
                if(!IsTextAllowed(text)) {
                    e.CancelCommand();
                }
            } else {
                e.CancelCommand();
            }
        }


    }

}
